#!python3
# -*- coding: utf-8

import socket
import sys
import logging

DEFAULT_PORT = 27015

def main():
    if len(sys.argv) != 2:
        print(f'usage: {sys.argv[0]} server-name')
        return 1
    
    addrinfos = socket.getaddrinfo(
        host=sys.argv[1],
        port=DEFAULT_PORT,
        family=socket.AF_UNSPEC,
        type=socket.SOCK_DGRAM,
        proto=socket.IPPROTO_UDP,
    )
    for family, socktype, protocol, canonname, addrinfo in addrinfos:
        try:
            with socket.socket(family=family, type=socktype, proto=protocol) as sock:
                try:
                    n = sock.sendto(b'this is a test', addrinfo)
                    print(f'Bytes Sent: {n}')
                    sock.shutdown(socket.SHUT_WR)
                    bs, ret_addr = sock.recvfrom(256)
                    ip, port = ret_addr
                    print(f'Bytes received: {len(bs)}, from {ip}:{port}')
                except Exception as e:
                    logging.exception(e)
                    return 1
        except Exception as e:
            logging.exception(e)
            return 1

if __name__=='__main__':
    sys.exit(main())